package glue

import (
	"encoding/json"
	"strings"
)

const (
	// for agent
	StatusNotReady = `notReady`
	StatusUnKnown  = `unknown`

	// for instance
	StatusInConfiguration = "InConfiguration"
	StatusInScheduling    = "InScheduling"
	StatusPending         = "Pending"
	StatusReady           = "Ready"
	StatusPause           = "Pause"
	StatusError           = "Error"
	StatusTerminating     = "Terminating"
	StatusTerminated      = "Terminated"

	InstanceTypeResourceSet = "resourceSet"
	InstanceTypePodSet      = "podSet"
	InstanceTypePod         = "pod"
	InstanceTypeContainer   = "container"
)

type Instance struct {
	Label      string `json:"label" yaml:"label" xorm:"label varchar(255) pk notnull unique('head')"`
	Version    string `json:"version" yaml:"version" xorm:"version varchar(15) default 'v0.0.1'"`
	Name       string `json:"name" yaml:"name" xorm:"name varchar(40) default 'what is the config name?'"`
	Describe   string `json:"describe" yaml:"describe" xorm:"describe varchar(40) default 'what is the config describe?'"`
	ConfigKind string `json:"kind" yaml:"kind" xorm:"kind varchar(20) default 'application'"`

	InstanceYaml       string `json:"instance_yaml" yaml:"instance_yaml" xorm:"instance_yaml TEXT"`
	InstanceServeLevel string `json:"instance_serve_level" yaml:"instance_serve_level " xorm:"instance_serve_level varchar(20) default 'bestEffort'"`
	InstanceType       string `json:"instance_type" yaml:"instance_type" xorm:"instance_type varchar(20) default 'container'"`

	InstanceGuid  string `json:"guid" yaml:"guid" xorm:"guid varchar(255) pk notnull unique('head')"`
	InstanceState string `json:"state" yaml:"state" xorm:"state varchar(20) default 'InConfiguration'"`
	InstanceNode  string `json:"node" yaml:"node" xorm:"node varchar(100)"`

	Tags string `json:"tags" yaml:"tags" xorm:"tags TEXT"`

	UserToken string `json:"user_token" yaml:"user_token" xorm:"user_token TEXT"`
}

func InstanceTypes() []string {
	return []string{InstanceTypeResourceSet, InstanceTypePodSet, InstanceTypePod, InstanceTypeContainer}
}

func InstanceStatus() []string {
	return []string{StatusInConfiguration, StatusInScheduling, StatusPending, StatusReady, StatusPause, StatusError, StatusTerminating, StatusTerminated}
}

func CreateInstanceFromConfig(cfgValues string, name, guid string) (string, error) {
	var cfg = Config{}
	if err := json.Unmarshal([]byte(cfgValues), &cfg); err != nil {
		return "", err
	}

	var label = strings.Replace(cfg.Label, "config", "instance", 1)
	var ins = Instance{
		Label:      label,
		Name:       name,
		Describe:   cfg.Describe,
		Version:    cfg.Version,
		ConfigKind: cfg.ConfigKind,

		InstanceServeLevel: cfg.InstanceServeLevel,
		InstanceType:       cfg.InstanceType,
		InstanceYaml:       cfg.InstanceYaml,

		InstanceGuid:  guid,
		InstanceState: StatusInConfiguration,

		Tags: cfg.Tags,
	}

	bts, _ := json.Marshal(ins)

	return string(bts), nil
}
